package com.xiaoq.sites.repository.impl;

import com.xiaoq.sites.entity.InterDicEntity;
import com.xiaoq.sites.repository.IInterDicRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class InterDicRepositoryImpl implements IInterDicRepository {
	
	@Autowired
	private Datastore datastore;

	private static final Logger LOG = LoggerFactory.getLogger(InterDicRepositoryImpl.class);

	@Override
	public boolean save(InterDicEntity interDicEntity) {
		if(interDicEntity != null && StringUtils.isBlank(interDicEntity.getId())){
			return false;
		}
		datastore.save(interDicEntity);
		return true;
	}

	@Override
	public boolean updateById(InterDicEntity interDicEntity) {
		if(interDicEntity == null || StringUtils.isEmpty(interDicEntity.getId())){
			return false;
		}

		Query<InterDicEntity> query = datastore.createQuery(InterDicEntity.class)
				.filter("_id =", interDicEntity.getId());
		UpdateOperations<InterDicEntity> update = datastore
				.createUpdateOperations(InterDicEntity.class);

		update.set("updatedAt", System.currentTimeMillis());
		if(StringUtils.isNotBlank(interDicEntity.getDicId())){
			update.set("dicId", interDicEntity.getDicId());
		}
		if(StringUtils.isNotBlank(interDicEntity.getDicValue())){
			update.set("dicValue", interDicEntity.getDicValue());
		}
		if(interDicEntity.getDicType() != null){
			update.set("dicType", interDicEntity.getDicType());
		}
		if(StringUtils.isNotBlank(interDicEntity.getDicTypeDesc())){
			update.set("dicTypeDesc", interDicEntity.getDicTypeDesc());
		}
		datastore.update(query, update);
		return true;
	}

	@Override
	public List<InterDicEntity> getAllInterDicList(Integer dicType, List<String> dicIdList) {
		Query<InterDicEntity> query = datastore.createQuery(InterDicEntity.class);
		if(dicType != null){
			query.filter("dicType", dicType);
		}
		if(CollectionUtils.isNotEmpty(dicIdList)){
			query.filter("dicId in", dicIdList);
		}
		return query.asList();
	}

}
